package tms.business.xml;

import tms.util.logging.Area;
import tms.util.logging.Logger;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import java.io.File;
import java.io.InputStream;

import static tms.util.logging.AreaType.BUSINESS;

@Local
@Stateless
public class XmlBindingService {
    @Inject @Area(BUSINESS)
    Logger logger;

    @SuppressWarnings("unchecked")
    public <T> T unmarshal(Class<T> clazz, File file) {
        T retVal = null;
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
            retVal = (T)jaxbContext.createUnmarshaller().unmarshal(file);
        } catch (JAXBException e) {
            logger.warning("Error during unmarshalling from file {0}", e, file.getName());
        }
        return retVal;
    }

    @SuppressWarnings("unchecked")
    public <T> T unmarshal(Class<T> clazz, InputStream inputStream) {
        T retVal = null;
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
            retVal = (T)jaxbContext.createUnmarshaller().unmarshal(inputStream);
        } catch (JAXBException e) {
            logger.warning("Error during unmarshalling from input stream", e);
        }
        return retVal;
    }
}
